/*-----------------------------------------------File Info------------------------------------------------
** File Name:               I2cWR.c  
** Last modified date:      20222620
** Last version:            V0.1
** Description:             
**--------------------------------------------------------------------------------------------------------            
** Created date:            20220620
** author:                  YLY
** Version:                 V0.1
** Descriptions:            I2c读写操作
**--------------------------------------------------------------------------------------------------------
*/
/*************************************************************
* 	include 
* 	头文件	
*************************************************************/
#include "I2cWR.h"
#include "appGpio.h"
#include "ctrl.h"

volatile teI2cWRFeedback geFeedback;
tsCfgI2c gtCfgI2cKey = KEY_I2C;
		
#define I2C_WR_DELAY()	taskDelayUs(10)	//taskDelayMs(10) osDirectiveDelayUs
#define I2C_TIMEROUT	100000u//单位 I2C_WR_DELAY(x)

static void callback(teFeedback eFeedback, uint8_t *pData, uint16_t size)
{
	I2CWR_DGB("\r\ncb%d\r\n",eFeedback);
	if(eFeedback == I2C_SUCCESS)
	{
		geFeedback = I2C_WR_SUCCESS;
	}
	else
	{
		geFeedback = I2C_WR_FAIL;
	}
}

uint8_t i2cWriteReg(uint8_t addr, uint8_t reg, uint8_t *pValue, uint8_t num)
{
	uint32_t i;
	
	uint8_t buf[4];	
	if(num > (sizeof(buf) - 1))
		return FAIL;
	
	buf[0] = reg;
	
	if(num)
		memcpy(buf+1, pValue, num);
	
	geFeedback = I2C_WR_IDLE;
	
	I2CWR_DGB("Wr:%x,%x\r\n",addr,reg);
	i2cMasterWrite(&gtCfgI2cKey, addr, buf, num+1, callback);
	i=0;
	while(geFeedback == I2C_WR_IDLE)
	{
		I2C_WR_DELAY();
		if(i++ > I2C_TIMEROUT)
		{
			I2CWR_ERR("WrTo\r\n");
			return FAIL;
		}
	}
	I2CWR_DGB("wrOk\r\n");
	if(geFeedback == I2C_WR_SUCCESS)
		return SUCCESS;
	I2CWR_ERR("WrER\r\n");
	return FAIL;
}

uint8_t i2cReadReg(uint8_t addr, uint8_t reg, uint8_t *pValue, uint8_t num)
{
	uint32_t i;
	uint8_t buf[8];	
	geFeedback = I2C_WR_IDLE;
	
	I2CWR_DGB("ReWr:addr=%x,reg=%x\r\n",addr,reg);	
	i2cMasterWrite(&gtCfgI2cKey, addr, &reg, 1, callback);
	i=0;
	while(geFeedback == I2C_WR_IDLE)
	{
		I2C_WR_DELAY();
		if(i++ > I2C_TIMEROUT)
		{
			I2CWR_ERR("ReWrTo\r\n");
			return FAIL;
		}
	}
	geFeedback = I2C_WR_SUCCESS;
	if(geFeedback == I2C_WR_SUCCESS)
	{
		geFeedback = I2C_WR_IDLE;
		I2CWR_DGB("ReRed,NUM=%d\r\n",num);

		i2cMasterRead(&gtCfgI2cKey, addr, pValue, num, callback);		
		i=0;
		while(geFeedback == I2C_WR_IDLE)
		{
			I2C_WR_DELAY();
			if(i++ > I2C_TIMEROUT)
			{
				I2CWR_ERR("ReReTo\r\n");
				return FAIL;
			}
		}	
		I2CWR_DGB("reVal:%x\r\n",*pValue);
		if(geFeedback == I2C_WR_SUCCESS)		
			return SUCCESS;
		I2CWR_ERR("fbReReErr,fb=%d\r\n",geFeedback);
	}
	I2CWR_ERR("fbReWrErr,fb=%d\r\n",geFeedback);
	return FAIL;
}

void i2cWRInit(void)
{
	static uint8_t init = false;
	if(!init)
	{
		init = true;
		i2cInit(&gtCfgI2cKey, KEY_CLK_RATE, KEY_I2C_SLAVE_ADDR0);			/* I2C初始化 */
	}
}



